package com.study.flink.java.day02_source;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;

import java.util.Properties;

//KafkaSource->并行的source
public class KafkaSource {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // kafka的partitions有3个，对应有3个source
        Properties props = new Properties();
        props.setProperty("bootstrap.servers", "node02:9092"); //kafka的broker地址
        props.setProperty("group.id", "gid-wc10");//指定组ID
        props.setProperty("auto.offset.reset", "earliest");//没有记录偏移量，第一次从最开始消费
        //props.setProperty("enable.auto.commit", "false");//自动提交偏移量

        // 用kafka的并行source，每一个组都要满足条件才会触发
        FlinkKafkaConsumer<String> wc10 = new FlinkKafkaConsumer<>("wc10", new SimpleStringSchema(), props);
        DataStream<String> lines = env.addSource(wc10);

        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndCount = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                // (单词,次数)
                return Tuple2.of(s, 1);
            }
        });

        // 聚合计算wordcount
        SingleOutputStreamOperator<Tuple2<String, Integer>> summed = wordAndCount.keyBy(0).sum(1);

        summed.print();

        env.execute("KafkaSource-java");

    }




}
